package com.jhgsys.internal.peccancy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.DictCodeConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.peccancy.constant.PeccancyConstant;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationDto;
import com.jhgsys.internal.peccancy.dto.PeccancyInformationQueryDto;
import com.jhgsys.internal.peccancy.entity.PeccancyInformation;
import com.jhgsys.internal.peccancy.entity.PeccancyModuleConfig;
import com.jhgsys.internal.peccancy.service.IPeccancyInformationService;
import com.jhgsys.internal.peccancy.service.IPeccancyModuleConfigService;
import com.jhgsys.internal.workflow.dto.WorkflowReviewRequestDto;
import com.jhgsys.internal.workflow.entity.WorkflowApply;
import com.jhgsys.internal.workflow.entity.WorkflowNode;
import com.jhgsys.internal.workflow.entity.WorkflowNodeReview;
import com.jhgsys.internal.workflow.service.IWorkflowApplyService;
import com.jhgsys.internal.workflow.service.IWorkflowInfoService;
import com.jhgsys.internal.workflow.service.IWorkflowNodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 违章审核记录 Controller
 *
 * @author Wanghw
 * @date 2024-08-14 10:38:38
 */
@Slf4j
@Validated
@Controller
public class PeccancyAuditRecordController extends BaseController {



    @Autowired
    private IPeccancyInformationService peccancyInformationService;
    @Autowired
    private IDictService dictService;

    @Autowired
    private IPeccancyModuleConfigService moduleConfigService;

    @Autowired
    private IWorkflowApplyService workflowApplyService;

    @Autowired
    private IWorkflowNodeService workflowNodeService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyAuditRecord")
    @RequiresPermissions("peccancyAuditRecord:view")
    public String peccancyAuditRecordIndex(Model model){
        setModel(model);
        return jumpPage("peccancy/peccancyAuditRecord/peccancyAuditRecordList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyAppealRecord")
    @RequiresPermissions("peccancyAppealRecord:view")
    public String peccancyAppealRecordIndex(Model model){
        setModel(model);
        return jumpPage("peccancy/peccancyAppealRecord/peccancyAppealRecordList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyIssuanceRecord")
    @RequiresPermissions("peccancyIssuanceRecord:view")
    public String peccancyIssuanceRecordIndex(Model model){
        setModel(model);
        return jumpPage("peccancy/peccancyIssuanceRecord/peccancyIssuanceRecordList");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyAuditRecord/update/{id}")
    @RequiresPermissions("peccancyAuditRecord:audit")
    public String peccancyAuditRecordUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        PeccancyInformationDto dto = peccancyInformationService.findPeccancyInformationDtoById(id);
        model.addAttribute("peccancyInformation", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        setModel(model);
        model.addAttribute("countYear",peccancyInformationService.countPeccancyByUserId(dto));
        if(StringUtils.isNotBlank(dto.getWorkflowApplyId())){
            model.addAttribute("workflowApplyId",dto.getWorkflowApplyId());
            WorkflowApply workflowApply = workflowApplyService.getById(dto.getWorkflowApplyId());
            model.addAttribute("workflowApply",workflowApply);
            if(null != workflowApply){
                WorkflowNode workflowNode = workflowNodeService.getById(workflowApply.getWorkflowNodeId());
                model.addAttribute("workflowNode",workflowNode);
            }
        }
        return jumpPage("peccancy/peccancyAuditRecord/peccancyAuditRecordEdit");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyAppealRecord/update/{id}")
    @RequiresPermissions("peccancyAppealRecord:appeal")
    public String peccancyAppealRecordUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        PeccancyInformationDto dto = peccancyInformationService.findPeccancyInformationDtoById(id);
        model.addAttribute("peccancyInformation", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        setModel(model);
        return jumpPage("peccancy/peccancyAppealRecord/peccancyAppealRecordEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "peccancyIssuanceRecord/update/{id}")
    @RequiresPermissions("peccancyIssuanceRecord:issuance")
    public String peccancyIssuanceRecordUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        PeccancyInformationDto dto = peccancyInformationService.findPeccancyInformationDtoById(id);
        model.addAttribute("peccancyInformation", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        setModel(model);
        return jumpPage("peccancy/peccancyIssuanceRecord/peccancyIssuanceRecordEdit");
    }




    /**
     * 审核查询（分页）
     * @author Wanghw
     * @date 2024-08-14 10:38:38
     */
    @GetMapping("peccancyAuditRecord/list")
    @ResponseBody
    @RequiresPermissions("peccancyAuditRecord:view")
    public FebsResponse peccancyAuditRecordList(QueryRequest request,
                                                @RequestParam(name = "startDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                                @RequestParam(name = "endDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                                @RequestParam(name = "projectName",required = false) String projectName,
                                                @RequestParam(name = "peccancyRealName",required = false) String peccancyRealName,
                                                @RequestParam(name = "tenantId",required = true) String tenantId) {
        PeccancyInformationQueryDto peccancyInformation = new PeccancyInformationQueryDto();
        if(StringUtils.isNotBlank(projectName)){
            peccancyInformation.setProjectName(projectName);
        }
        if(StringUtils.isNotBlank(peccancyRealName)){
            peccancyInformation.setPeccancyRealName(peccancyRealName);
        }

        peccancyInformation.setStartDate(startDate);
        peccancyInformation.setEndDate(endDate);
        peccancyInformation.setTenantId(tenantId);
        List<String> auditList = Arrays.asList(PeccancyConstant.INFORMATION_STATUS.WAITING_AUDIT,PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL);
        peccancyInformation.setStatus(String.join(StringPool.COMMA, auditList));
        Map<String, Object> dataTable = getDataTable(this.peccancyInformationService.findPeccancyInformationDtoPage(request, peccancyInformation));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 申诉查询（分页）
     * @author Wanghw
     * @date 2024-08-14 10:38:38
     */
    @GetMapping("peccancyAppealRecord/list")
    @ResponseBody
    @RequiresPermissions("peccancyAppealRecord:view")
    public FebsResponse peccancyAppealRecordList(QueryRequest request,
                                                @RequestParam(name = "startDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                                @RequestParam(name = "endDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                                @RequestParam(name = "projectName",required = false) String projectName,
                                                @RequestParam(name = "peccancyRealName",required = false) String peccancyRealName,
                                                @RequestParam(name = "status",required = true) String status,
                                                @RequestParam(name = "tenantId",required = true) String tenantId) {
        PeccancyInformationQueryDto peccancyInformation = new PeccancyInformationQueryDto();
        if(StringUtils.isNotBlank(projectName)){
            peccancyInformation.setProjectName(projectName);
        }
        if(StringUtils.isNotBlank(peccancyRealName)){
            peccancyInformation.setPeccancyRealName(peccancyRealName);
        }
        if(!hasHeadCompanyRole()){
//            User user = getCurrentUser();
//            String s = user.getDeptLeaderFlg();
//            //如果不是总公司，且时部门主管
//            if(PeccancyConstant.IS_OR_NO.IS.equals(getCurrentUser().getDeptLeaderFlg())){
//                peccancyInformation.setPeccancyUserDeptId(getCurrentUser().getDeptId());
//            }
        }
        peccancyInformation.setStartDate(startDate);
        peccancyInformation.setEndDate(endDate);
        peccancyInformation.setTenantId(tenantId);
        peccancyInformation.setStatus(status);
        Map<String, Object> dataTable = getDataTable(this.peccancyInformationService.findPeccancyInformationDtoPage(request, peccancyInformation));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 签发查询（分页）
     * @author Wanghw
     * @date 2024-08-14 10:38:38
     */
    @GetMapping("peccancyIssuanceRecord/list")
    @ResponseBody
    @RequiresPermissions("peccancyIssuanceRecord:view")
    public FebsResponse peccancyIssuanceRecordList(QueryRequest request,
                                                @RequestParam(name = "startDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                                @RequestParam(name = "endDate",required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                                @RequestParam(name = "projectName",required = false) String projectName,
                                                @RequestParam(name = "peccancyRealName",required = false) String peccancyRealName,
                                                @RequestParam(name = "status",required = true) String status,
                                                @RequestParam(name = "tenantId",required = true) String tenantId) {
        PeccancyInformationQueryDto peccancyInformation = new PeccancyInformationQueryDto();
        if(StringUtils.isNotBlank(projectName)){
            peccancyInformation.setProjectName(projectName);
        }
        if(StringUtils.isNotBlank(peccancyRealName)){
            peccancyInformation.setPeccancyRealName(peccancyRealName);
        }
        peccancyInformation.setStartDate(startDate);
        peccancyInformation.setEndDate(endDate);
        peccancyInformation.setTenantId(tenantId);
        peccancyInformation.setStatus(status);
        Map<String, Object> dataTable = getDataTable(this.peccancyInformationService.findPeccancyInformationDtoPage(request, peccancyInformation));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 提交审核
     * @author Wanghw
     * @date 2024-08-14 10:38:38
     */
    @Log("提交审核")
    @PostMapping("peccancyAuditRecord")
    @ResponseBody
    @RequiresPermissions("peccancyAuditRecord:audit")
    public FebsResponse addPeccancyAuditRecord(@RequestBody PeccancyInformation peccancyInformation) throws FebsException {

        try {
            checkAuditParams(peccancyInformation);
            String informationId = peccancyInformation.getInformationId();
            PeccancyInformation queryInformation = peccancyInformationService.findPeccancyInformationById(informationId);
            if(ObjectUtils.isEmpty(queryInformation)){
                return new FebsResponse().fail().message("未找到对应违章信息");
            }

            if(!PeccancyConstant.INFORMATION_STATUS.WAITING_AUDIT.equals(queryInformation.getStatus())
               && !PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL.equals(queryInformation.getStatus())){
                return new FebsResponse().fail().message("该记录非可审核状态，无法审核！");
            }

            if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus())){
                setAutoAuditAndIssuance(peccancyInformation);
            }
            peccancyInformation.setAuditUserId(getCurrentUser().getUserId());
            peccancyInformation.setCreatedBy(getCurrentUser().getUserName());
            peccancyInformation.setAuditRealName(getCurrentUser().getUname());
            peccancyInformation.setAuditDate(new Date());
            peccancyInformationService.auditPeccancyInformation(peccancyInformation,queryInformation.getStatus());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增PeccancyAuditRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }



    /**
     * 违章申诉
     *
     * @author wanghw
     * @date 2024-08-12 09:46:29
     */
    @Log("违章申诉")
    @PostMapping("peccancyAppealRecord")
    @ResponseBody
    @RequiresPermissions("peccancyAppealRecord:appeal")
    public FebsResponse peccancyAppealRecord(@RequestBody PeccancyInformation peccancyInformation) throws FebsException {
        try {
            if(StringUtils.isBlank(peccancyInformation.getInformationId())){
                throw  new FebsException("未上传对应违章信息ID");
            }
            if(StringUtils.isBlank(peccancyInformation.getAppealReason())){
                throw  new FebsException("请输入申诉理由！");
            }
            PeccancyInformation queryData = peccancyInformationService.findPeccancyInformationById(peccancyInformation.getInformationId());
            if(ObjectUtils.isEmpty(queryData)){
                return new FebsResponse().fail().message("未找到对应违章信息");
            }
            if(PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(queryData.getStatus())){
                return new FebsResponse().fail().message("该记录已签发，无法申诉！");
            }
            peccancyInformation.setAppealUserId(getCurrentUser().getUserId());
            peccancyInformation.setAppealTime(new Date());
            peccancyInformation.setAppealRealName(getCurrentUser().getUname());
            peccancyInformation.setAppeaFlg(PeccancyConstant.IS_OR_NO.IS);
            peccancyInformation.setAppealStatus(PeccancyConstant.IS_OR_NO.NO);
            peccancyInformation.setUpdatedBy(getCurrentUser().getUserName());
            this.peccancyInformationService.updatePeccancyInformation(peccancyInformation);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "申诉失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 违章签发
     *
     * @author wanghw
     * @date 2024-08-12 09:46:29
     */
    @Log("违章签发")
    @PostMapping("peccancyIssuanceRecord")
    @ResponseBody
    @RequiresPermissions("peccancyIssuanceRecord:issuance")
    public FebsResponse peccancyIssuanceRecord(@RequestBody PeccancyInformation peccancyInformation) throws FebsException {
        try {
            checkIssuanceParams(peccancyInformation);
            PeccancyInformation queryData = peccancyInformationService.findPeccancyInformationById(peccancyInformation.getInformationId());
            if(ObjectUtils.isEmpty(queryData)){
                return new FebsResponse().fail().message("未找到对应违章信息");
            }

            peccancyInformation.setIssuanceUserId(getCurrentUser().getUserId());
            peccancyInformation.setPeccancyObject(queryData.getPeccancyObject());
            peccancyInformation.setIssuanceDate(new Date());
            peccancyInformation.setIssuanceRealName(getCurrentUser().getUname());
            if (PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL.equals(peccancyInformation.getStatus())
                    || PeccancyConstant.INFORMATION_STATUS.DELETE.equals(peccancyInformation.getStatus())) {
                //如果是签发退回，或者作废，则属于申诉成功
                peccancyInformation.setAppealStatus(PeccancyConstant.APPEAL_STATUS.APPEALED);
            } else if (PeccancyConstant.INFORMATION_STATUS.ISSUANCED.equals(peccancyInformation.getStatus())) {
                //如果是签发，则属于申诉失败
                peccancyInformation.setAppealStatus(PeccancyConstant.APPEAL_STATUS.APPEAL_FAIL);
            }
            peccancyInformation.setUpdatedBy(getCurrentUser().getUserName());
            this.peccancyInformationService.issuancePeccancyInformation(peccancyInformation);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "签发失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 保存线上审核流程
     *
     * @author gy
     * @date 2024-09-14 09:46:29
     */
    @Log("保存线上审核流程")
    @PostMapping("saveOnlineProcess")
    @ResponseBody
    public FebsResponse saveOnlineProcess(@RequestBody PeccancyInformationDto peccancyInformation) throws FebsException {
        try {
            checkAuditParams(peccancyInformation);
            String informationId = peccancyInformation.getInformationId();
            PeccancyInformation queryInformation = peccancyInformationService.findPeccancyInformationById(informationId);
            if(ObjectUtils.isEmpty(queryInformation)){
                return new FebsResponse().fail().message("未找到对应违章信息");
            }
            //查询apply表，如果当前的上个节点为空则判断为第一次审核
            LambdaQueryWrapper<WorkflowApply> wrapper= new LambdaQueryWrapper<>();
            wrapper.eq(WorkflowApply::getBusinessId,peccancyInformation.getInformationId());
            wrapper.eq(WorkflowApply::getDeletedFlg,"0");
            wrapper.last("limit 1");
            WorkflowApply workflowApply = workflowApplyService.getOne(wrapper);
            if(null != workflowApply){
                if(StringUtils.isBlank(workflowApply.getLastWorkflowNodeId())){
                    peccancyInformation.setAuditUserId(getCurrentUser().getUserId());
                    peccancyInformation.setAuditRealName(getCurrentUser().getUname());
                    peccancyInformation.setAuditDate(new Date());
                }
            }

            WorkflowReviewRequestDto workflowReviewRequestDto =new WorkflowReviewRequestDto();
            workflowReviewRequestDto.setWorkflowApplyId(peccancyInformation.getWorkflowApplyId());
            workflowReviewRequestDto.setCheckWorkflowNodeId(peccancyInformation.getWorkflowNodeId());
            workflowReviewRequestDto.setDefaultReviewResult(peccancyInformation.getDefaultReviewResult());
            workflowReviewRequestDto.setUserName(getCurrentUser().getUserName());
            workflowReviewRequestDto.setRealNMame(getCurrentUser().getUname());
            workflowReviewRequestDto.setReviewRemark(peccancyInformation.getAuditRemark());
            workflowApplyService.submitWorkflowReview(workflowReviewRequestDto);

            if(("2").equals(peccancyInformation.getDefaultReviewResult())){
                peccancyInformation.setStatus("3");
            }else{
                LambdaQueryWrapper<WorkflowApply> wrappers=new LambdaQueryWrapper<>();
                wrappers.eq(WorkflowApply::getDeletedFlg,"0");
                wrappers.eq(WorkflowApply::getBusinessId,peccancyInformation.getInformationId());
                wrappers.orderByDesc(WorkflowApply::getCreatedTime);
                wrappers.last("limit 1");
                WorkflowApply applyServiceOne = workflowApplyService.getOne(wrappers);
                if(("6").equals(applyServiceOne.getWorkflowApplyStatus())){
                    peccancyInformation.setStatus("4");
                }
            }
            peccancyInformationService.auditPeccancyInformation(peccancyInformation,queryInformation.getStatus());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增PeccancyAuditRecord失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * set MOdel
     * @param model
     * @return
     */
    private Model setModel(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        model.addAttribute("peccancyRootCauseList", dictService.findDictByCode(DictCodeConstant.SAFETY_PECCANCY_ROOT_REASON));
        model.addAttribute("jobOperationList", dictService.findDictByCode(DictCodeConstant.SAFETY_JOB_OPERATION));
        model.addAttribute("peccancyTypeList", dictService.findDictByCode(DictCodeConstant.SAFETY_PECCANCY_TYPE));
        model.addAttribute("peccancyDisposeFormList", dictService.findDictByCode(DictCodeConstant.SAFETY_PECCANCY_DISPOSE_FORM));
        return model;
    }


    /**
     * 校验审核参数
     * @param peccancyInformation
     * @throws FebsException
     */
    private void checkAuditParams(PeccancyInformation peccancyInformation) throws FebsException {
        if(StringUtils.isBlank(peccancyInformation.getInformationId())){
            throw  new FebsException("未找到对应违章信息ID");
        }
        if(PeccancyConstant.INFORMATION_STATUS.AUDIT_FAIL.equals(peccancyInformation.getStatus())
                && StringUtils.isBlank(peccancyInformation.getAuditRemark())){
            throw  new FebsException("请输入审核退回原因！");
        }
        if(StringUtils.isBlank(peccancyInformation.getPeccancyNature())){
            throw  new FebsException("请输入违章性质！");
        }
        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus())
                && StringUtils.isNotBlank(peccancyInformation.getPenaltyAmountFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getPenaltyAmountFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getPenaltyAmount())){
            throw  new FebsException("请输入罚款金额！");
        }else if(PeccancyConstant.INFORMATION_STATUS.AUDIT_FAIL.equals(peccancyInformation.getStatus())){
            peccancyInformation.setPenaltyAmountFlg(null);
            peccancyInformation.setPenaltyAmount(null);
        }


        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus())
                && StringUtils.isNotBlank(peccancyInformation.getPenaltyScoreFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getPenaltyScoreFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getPenaltyScore())){
            throw  new FebsException("请输入扣除分数！");
        }else  if(PeccancyConstant.INFORMATION_STATUS.AUDIT_FAIL.equals(peccancyInformation.getStatus())){
            peccancyInformation.setPenaltyScoreFlg(null);
            peccancyInformation.setPenaltyScore(null);
        }

        if(PeccancyConstant.INFORMATION_STATUS.WAITING_ISSUANCE.equals(peccancyInformation.getStatus())
                && StringUtils.isNotBlank(peccancyInformation.getLearnVideoFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getLearnVideoFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getLearnVideoUrl())){
//            throw  new FebsException("请输入视频学习内容！");
        }else  if(PeccancyConstant.INFORMATION_STATUS.AUDIT_FAIL.equals(peccancyInformation.getStatus())){
            peccancyInformation.setLearnVideoFlg(null);
//            peccancyInformation.setPenaltyScore(null);
        }
    }

    /**
     * 校验签发参数
     * @param peccancyInformation
     * @throws FebsException
     */
    private void checkIssuanceParams(PeccancyInformation peccancyInformation) throws FebsException {
        if(StringUtils.isBlank(peccancyInformation.getInformationId())){
            throw  new FebsException("未找到对应违章信息ID");
        }
        if(StringUtils.isBlank(peccancyInformation.getIssuanceRemark())){
            throw  new FebsException("请输入签发备注！");
        }
        if(StringUtils.isBlank(peccancyInformation.getPeccancyNature())){
            throw  new FebsException("请输入违章性质！");
        }
        if(StringUtils.isNotBlank(peccancyInformation.getPenaltyAmountFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getPenaltyAmountFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getPenaltyAmount())){
            throw  new FebsException("请输入罚款金额！");
        }

        if(StringUtils.isNotBlank(peccancyInformation.getPenaltyScoreFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getPenaltyScoreFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getPenaltyScore())){
            throw  new FebsException("请输入扣除分数！");
        }

        if(StringUtils.isNotBlank(peccancyInformation.getLearnVideoFlg())
                && PeccancyConstant.IS_OR_NO.IS.equals(peccancyInformation.getLearnVideoFlg())
                && ObjectUtils.isEmpty(peccancyInformation.getLearnVideoUrl())){
//            throw  new FebsException("请输入视频学习内容！");
        }else  if(PeccancyConstant.INFORMATION_STATUS.ISSUANCE_FAIL.equals(peccancyInformation.getStatus())){
            peccancyInformation.setLearnVideoFlg(null);
            peccancyInformation.setLearnVideoUrl(null);
        }
    }


    /**
     * 判断是否自动审核或者自动签发
     * @param peccancyInformation
     */
    private void setAutoAuditAndIssuance(PeccancyInformation peccancyInformation){
        PeccancyModuleConfig moduleConfig = moduleConfigService.findPeccancyModuleConfigByTenantId(getCurrentTenantId());
        if(ObjectUtils.isNotEmpty(moduleConfig)){
            //有模块化配置
            if(PeccancyConstant.IS_OR_NO.IS.equals(moduleConfig.getIssuedSwitch())){
                //审核开关关闭  ， 签发开关开启
                if(PeccancyConstant.CONFIG_TYPE.AUTO.equals(moduleConfig.getIssuedType())){
                    log.info("有模块配置，签发开关打开，已配置自动签发");
                    //自动签发流程

                }else {
                    //手动签发流程
                    log.info("有模块配置，，签发开关打开，已配置手动签发");
                }
            }else {
                log.info("有模块配置，签发开关关闭，直接自动签发");
                setAutoIssuance(peccancyInformation);
            }

        }else{
            log.info("未进行模块配置，默认直接签发");
            //没有模块审核签发配置  直接签发
            setAutoIssuance(peccancyInformation);
        }


    }

    /**
     * 自动签发状态
     * @param peccancyInformation
     */
    private void setAutoIssuance(PeccancyInformation peccancyInformation){
        peccancyInformation.setStatus(PeccancyConstant.INFORMATION_STATUS.ISSUANCED);
        peccancyInformation.setIssuanceDate(new Date());
        peccancyInformation.setIssuanceRemark("系统自动签发");
        peccancyInformation.setIssuanceRealName("系统");
    }

}
